<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="top"
    >  
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据源名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入数据源名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据源类型">
            <el-input v-if="formData.type=='HTTP'" :value="'HTTP接口'" disabled />
			<el-input v-else-if="formData.type=='MQTT'" :value="'MQTT'" disabled />
			<el-input v-else-if="formData.type=='DATABASE'" :value="'数据库'" disabled />
			<el-input v-else-if="formData.type=='WEBSOCKET'" :value="'WebSocket'" disabled />
			<el-input v-else-if="formData.type=='EXCEL'" :value="'EXCEL'" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入数据源描述"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="true">启用</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { BasicField } from '@/components/DataWorkflow/types/data-collect.ts'

const emits = defineEmits(['update:basic'])
const props = defineProps<{ 
  data: BasicField
}>()

const formData = ref<BasicField>({ ...props.data })
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules<BasicField>>({
  name: [
    { required: true, message: '请输入接口名称', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择接口类型', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' }
  ],
  description: [
    { min: 2, max: 250, message: '长度在 2 到 250 个字符', trigger: 'blur' }
  ],
})

watch(() => props.data, (val: BasicField) => {
  formData.value = val || {}
}, { immediate: true, deep: true })

const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch {
    return false
  }
}

defineExpose({
  validate
})
</script>